import axios from 'axios'
import { box } from './mobx/box'
import { message } from 'antd';
let controller = new AbortController();

let cancelToken = axios.CancelToken;

const request = axios.create({
    baseURL: 'https://jsonplaceholder.typicode.com/',
    // timeout: 1000,
    headers: { 'X-Custom-Header': 'foobar' },
    signal: controller.signal,
});

let pending: Array<any> = []
// 判断是否有重复请求
let isRepeat = (config: any) => {
    console.log('pending', pending);
    pending.forEach((item, index) => {
        if (item.u === config.url.split('?')[0] + '-' + config.method) {
            pending[index].f()
            pending.splice(index, 1)
        }
    })
}

// 添加请求拦截器
request.interceptors.request.use((config: any) => {
    isRepeat(config)
    config.cancelToken = new cancelToken(c => {
        pending.push({ u: config.url.split('?')[0] + '-' + config.method, f: c })
    })
    // box.setLoading(true);
    // 在发送请求之前做些什么
    return config;
}, (error) => {
    console.log(error)
    // 对请求错误做些什么
    message.error(error)
    return Promise.reject(error);
});

// 添加响应拦截器
request.interceptors.response.use((response) => {
    let identity = response.config.url + '-' + response.config.method;
    let index = pending.findIndex(item => item.u === identity);
    pending.splice(index, 1);

    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    message.success(response.status)
    box.setLoading(false);
    return response.data;

}, (error) => {
    if (error.name === 'CanceledError') {
        message.error('请求取消')
    } else {
        Promise.reject(error);
    }
    box.setLoading(false);
    return error
});
// 取消请求
export const cancel = () => {
    pending.forEach(item=>{
        item.f()
    })
}


export default request;